import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'
import NProgress from 'nprogress'
import "nprogress/nprogress.css"

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

//全局前置守卫函数
router.beforeEach((to,from,next)=>{
  //获取token
  var token = localStorage.getItem('token');
  if( token ){ //已登录
    if( to.path == '/login' ){ // 想要去往登录页
      next('/');
    }else{ //想要去往其他页
      next();
    }
  }else{ //未登录
    if( to.path == '/login' || to.path == '/register' ){ // 想要去往登录页/注册页
      next();
    }else{ //想要去往其他页
      next('/login');
    }
  }  

  //动态修改网页标题
  document.title = to.meta.title;

  //开启进度条动画
  NProgress.start();

})

//全局后置守卫函数
router.afterEach((to,from)=>{
  //关闭进度条动画
  NProgress.done();
})

export default router
